package cn.lingyangwl.framework.rabbitmq.entity;

import cn.lingyangwl.framework.rabbitmq.callback.RabbitSendFailMqMessage;
import cn.lingyangwl.framework.rabbitmq.config.RabbitmqExtProperties;
import cn.lingyangwl.framework.tool.core.exception.Assert;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 转换类
 *
 * @author shenguangyang
 */
@Component
public class Conversion {
    private static RabbitmqExtProperties rabbitmqExtProperties;

    @Autowired
    public Conversion(RabbitmqExtProperties rabbitmqExtProperties) {
        Conversion.rabbitmqExtProperties = rabbitmqExtProperties;
    }

    public static RabbitSendFailMqMessage to(CorrelationData correlationData) {
        ReturnedMessage returned = correlationData.getReturned();
        // 返回的 ReturnedMessage 是空很有可能是交换机或者队列不存在问题
        Assert.notNull(returned, "ReturnedMessage is null");
        RabbitSendFailMqMessage rabbitMqMessage = new RabbitSendFailMqMessage();
        rabbitMqMessage.setMessage(returned.getMessage().toString());
        rabbitMqMessage.setMsgId(correlationData.getId());
        rabbitMqMessage.setExchange(returned.getExchange());
        rabbitMqMessage.setRetryCount(rabbitmqExtProperties.getRetry().getMaxAttempts());
        rabbitMqMessage.setRoutingKey(returned.getRoutingKey());
        return rabbitMqMessage;
    }
}
